<script setup lang="ts">
import { RoleApi } from '@/apis'
import { useConfirm, useRole } from '@/hooks'
import RoleFormPanel from './RoleFormPanel.vue'
import RoleTabPermission from './RoleTabPermission.vue'
import RoleTabUser from './RoleTabUser.vue'
import RoleListRightMenu from './RoleTreeRightMenu.vue'

defineOptions({ name: 'Role' })

// 角色列表
const { roleList: treeData, getRoleList: getTreeData, loading: treeLoading } = useRole()

// 根据选中角色查询
const selectedRole = ref<RoleApi.RoleResp>()
const onTreeNodeSelect = (key: string, node: RoleApi.RoleResp) => {
  selectedRole.value = node
}

// 角色管理
const RoleFormPanelRef = ref<InstanceType<typeof RoleFormPanel>>()
const onCreateRole = () => {
  RoleFormPanelRef.value?.create()
}

const onMenuItemClick = (action, data) => {
  if (action === 'detail') {
    RoleFormPanelRef.value?.open(data.id)
  }

  if (action === 'delete') {
    return useConfirm(() => RoleApi.remove(data.id), () => getTreeData(), {
      content: `是否确定删除该条数据？`,
      showModal: true,
    })
  }
}

onMounted(() => {
  getTreeData()
})
</script>

<template>
  <ProPage title="权限管理" description="左侧选择角色后，可以对角色的权限列表和用户进行调整">
    <TreeTableLayout>
      <template #left>
        <ListTree
          :loading="treeLoading"
          :data="treeData"
          @select="onTreeNodeSelect"
        >
          <template #extra>
            <a-button v-permission="['system:org:manage']" class="ml" type="primary" @click="onCreateRole">
              <icon-plus />
            </a-button>
          </template>
          <template #node="nodeData">
            <div class="flex-row-between-center">
              <span>{{ nodeData.name }}({{ nodeData.code }})</span>
              <a-tag v-if="nodeData.preserved" color="green" size="small">
                预置
              </a-tag>
            </div>
          </template>
          <template #action="nodeData">
            <RoleListRightMenu
              v-permission="'system:org:manage'"
              :data="nodeData"
              @menu-item-click="onMenuItemClick"
            />
          </template>
        </ListTree>
      </template>
      <template #right>
        <a-tabs default-active-key="1" lazy-load>
          <a-tab-pane key="1" title="资源权限">
            <RoleTabPermission :role="selectedRole" />
          </a-tab-pane>
          <a-tab-pane key="2" title="角色成员">
            <RoleTabUser :role="selectedRole" />
          </a-tab-pane>
        </a-tabs>
      </template>
    </TreeTableLayout>
    <RoleFormPanel ref="RoleFormPanelRef" @change="getTreeData" />
  </ProPage>
</template>

<style lang="less" scoped></style>
